<template>
  <div class="container">
    <div class="header">
      <h1>用户积分管理</h1>
    </div>
    
    <el-card class="table-card" v-loading="loading">
      <div class="top-actions">
        <el-button type="primary" @click="openAdjustDialog()">手动调整积分</el-button>
        <el-button @click="fetchData">刷新数据</el-button>
      </div>
      
      <el-table 
        :data="pointsList" 
        style="width: 100%" 
        border
        stripe
        highlight-current-row
      >
        <el-table-column prop="id" label="ID" width="70" align="center" />
        <el-table-column prop="userId" label="用户ID" width="130" align="center" />
        <el-table-column label="用户名称" min-width="150">
          <template #default="scope">
            <span>{{ getUserName(scope.row.userId) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="pointsNumbers" label="积分数量" width="100" align="center">
          <template #default="scope">
            <span class="points-number">{{ scope.row.pointsNumbers }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="160" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="110" align="center">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary"
              @click="openAdjustDialog(scope.row)"
            >调整积分</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 积分调整对话框 -->
    <el-dialog
      v-model="adjustDialogVisible"
      title="调整积分"
      width="500px"
    >
      <el-form :model="adjustForm" ref="adjustFormRef" label-width="120px">
        <el-form-item label="用户ID" prop="userId" :rules="[{ required: true, message: '请输入用户ID', trigger: 'blur' }]">
          <el-input 
            v-model.number="adjustForm.userId"
            type="number"
            placeholder="请输入用户ID"
            :disabled="!!selectedUser"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="当前积分">
          <span v-if="selectedUser" class="current-points">{{ selectedUser.pointsNumbers }}</span>
          <span v-else>--</span>
        </el-form-item>
        
        <el-form-item label="调整数量" prop="adjustment" :rules="[{ required: true, message: '请输入调整数量', trigger: 'blur' }]">
          <el-input-number
            v-model="adjustForm.adjustment"
            :min="-1000"
            :max="1000"
            placeholder="请输入调整数量"
          ></el-input-number>
          <span class="form-tip">负数为减少积分，正数为增加积分</span>
        </el-form-item>
        
        <el-form-item label="调整后积分">
          <span v-if="selectedUser" :class="{'increase': adjustForm.adjustment > 0, 'decrease': adjustForm.adjustment < 0}">
            {{ selectedUser.pointsNumbers + (adjustForm.adjustment || 0) }}
          </span>
          <span v-else>--</span>
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input 
            v-model="adjustForm.remark" 
            type="textarea"
            placeholder="请输入调整原因或备注信息"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="adjustDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAdjustPoints" :loading="adjusting">确认调整</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserPointsList, adjustUserPoints } from '@/api/points'

const loading = ref(false)
const adjusting = ref(false)
const pointsList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const adjustDialogVisible = ref(false)
const adjustFormRef = ref(null)
const selectedUser = ref(null)

// 积分调整表单
const adjustForm = reactive({
  userId: null,
  adjustment: 0,
  remark: ''
})

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '--'
  const date = new Date(dateStr)
  if (isNaN(date.getTime())) return dateStr
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 获取用户名称（此处应根据实际情况从用户表中获取）
const getUserName = (userId) => {
  if (!userId) return '--'
  // 根据用户ID生成用户名称，这里可以修改为从用户表中获取
  return `用户${userId}`
}

// 打开调整积分对话框
const openAdjustDialog = (row) => {
  selectedUser.value = row || null
  adjustForm.userId = row ? row.userId : null
  adjustForm.adjustment = 0
  adjustForm.remark = ''
  adjustDialogVisible.value = true
}

// 处理积分调整
const handleAdjustPoints = async () => {
  if (!adjustForm.userId) {
    ElMessage.warning('请先输入用户ID')
    return
  }
  
  if (!adjustForm.adjustment) {
    ElMessage.warning('请输入调整数量')
    return
  }
  
  // 确认对话框
  try {
    await ElMessageBox.confirm(
      `确定要为用户ID ${adjustForm.userId} ${adjustForm.adjustment > 0 ? '增加' : '减少'} ${Math.abs(adjustForm.adjustment)} 积分吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch (e) {
    return // 用户取消操作
  }
  
  adjusting.value = true
  try {
    const response = await adjustUserPoints(adjustForm.userId, adjustForm.adjustment)
    if (response.code === 200) {
      ElMessage.success('积分调整成功')
      adjustDialogVisible.value = false
      fetchData()
    } else {
      ElMessage.error(response.message || '积分调整失败')
    }
  } catch (error) {
    console.error('积分调整失败', error)
    ElMessage.error('积分调整失败，请重试')
  } finally {
    adjusting.value = false
  }
}

// 获取用户积分列表
const fetchData = async () => {
  loading.value = true
  try {
    const response = await getUserPointsList(currentPage.value, pageSize.value)
    if (response.code === 200 && response.data) {
      // 处理分页数据
      if (response.data.records) {
        pointsList.value = response.data.records
        total.value = response.data.total || 0
      } else {
        pointsList.value = Array.isArray(response.data) ? response.data : [response.data]
        total.value = pointsList.value.length
      }
    } else {
      ElMessage.error(response.message || '获取积分数据失败')
    }
  } catch (error) {
    console.error('获取积分数据失败', error)
    ElMessage.error('获取积分数据失败')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchData()
}

// 处理每页显示条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchData()
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
  
  .header {
    margin-bottom: 20px;
    
    h1 {
      font-size: 24px;
      margin: 0;
    }
  }
  
  .table-card {
    margin-bottom: 20px;
    
    .top-actions {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 15px;
      
      .el-button {
        margin-left: 10px;
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .form-tip {
    margin-left: 10px;
    color: #909399;
    font-size: 13px;
  }

  .points-number {
    font-weight: bold;
    color: #409EFF;
  }

  .current-points {
    font-weight: bold;
    font-size: 16px;
  }
  
  .increase {
    color: #67C23A;
    font-weight: bold;
  }
  
  .decrease {
    color: #F56C6C;
    font-weight: bold;
  }

  :deep(.el-table) {
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: bold;
    }
    
    td {
      padding: 10px 0;
    }
  }
}
</style> 